package com.audaque.springboot.foshanupload.web.zookeeperdemo.controller;

import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.integration.zookeeper.lock.ZookeeperLockRegistry;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;


@RestController
@RequestMapping("zookeeperIntegration")
@Log4j2
public class ZookeeperIntegrationController {

    @Autowired
    private ZookeeperLockRegistry zookeeperLockRegistry;


    @Autowired
    private ThreadPoolExecutor threadPoolExecutor;


    @GetMapping("/test2")
    public void test2() {

        while (true) {
            threadPoolExecutor.execute(new Runnable() {
                @Override
                public void run() {
                    run2();
                }
            });
        }

    }

    private void run2() {
        Lock lock = zookeeperLockRegistry.obtain("zookeeper");
        try {
            //尝试在指定时间内加锁，如果已经有其他锁锁住，获取当前线程不能加锁，则返回false，加锁失败；加锁成功则返回true
            if (lock.tryLock(3, TimeUnit.SECONDS)) {
                log.debug("lock is ready");
            } else {
                log.debug("lock isnot ready");
            }
        } catch (InterruptedException e) {
            log.error("obtain lock error", e);
        } finally {
            lock.unlock();
        }
    }


}